import {getLocalStorageJson} from "@/util/utilString";
import modal from "@/customize/modal";
import alert from "@/customize/alert";

// 默认背景图片
const BACKGROUND_IMAGE = "./resources/static/music.svg";
// 项目路径
const publicPath = process.env.BASE_URL;
// 音乐播放器
const audio = new Audio();
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();// 计时器

let timer = null;

// 播放器
const player = {
    // 是否在播放
    isPlay: false,
    // 是否播放成功，1成功，0失败，-1初始化
    isPlaySuccess: -1,
    // 播放状态
    playStartList: ['循环播放', '单曲循环', '随机播放'],
    playStart: 0,
    // 图片转动速度
    imageSpeed: 1,
    // 初始时长
    initTime: 0,
    // 当前播放进度
    currentTime: 0,
    // 播放总时长
    duration: 0,
    // 浏览器缓存
    cache: 0,
    // 正在播放id
    id: '-1',
    // 默认名称
    name: '',
    // 默认标题
    title: '未知歌名',
    // 默认歌手
    artist: '未知歌手',
    // 默认专辑
    album: '未知专辑',
    // 默认路径
    url: '',
    // 默认封面
    image: BACKGROUND_IMAGE,
};

// 播放列表
let musicList = [];

/* 数据列表
collectionList 收藏列表
historyList 历史记录
musicList 播放列表
 */

let musicListIndex = 0;

/**
 * 第一步<br />
 * 标题：在开启播放前，添加遮罩，检测是否播放成功，主要适用于网络歌曲
 *
 * 变量：music，歌曲信息<br />
 * 变量：obj，歌曲信息<br />
 */
function playModal(music, obj = {modalNo: true}) {
    // 是否开启遮罩
    obj.modalNo ? modal.onModal() : "";
    addPlay(music, obj);

    let isPlaySuccess;
    let time = 100;
    let interval2 = setInterval(() => {
        time += 100;
        isPlaySuccess = player.isPlaySuccess;
        if (isPlaySuccess !== -1 || time > 5000) {
            modal.offModal();
            clearInterval(interval2);
            if (isPlaySuccess !== 1) {
                music.isPlay = false;
                alert.dangerAlert(music.title + "播放失败！");
                // 如果播放失败，标记音乐为不能播放状态
                if (obj.type === "collection") {
                    cannotPlay(music.id);
                }
            } else {
                music.isPlaying = true;
            }
        }
    }, 100);
}

/**
 * 第二步<br />
 * 标题：添加音乐到播放列表并播放
 *
 * 变量：music，一首或多首。<br />
 * 变量：type=one|list，添加一首或添加多首。<br />
 * 变量：isPlay，添加后是否播放。<br />
 * 变量：isAddHistory，是否添加到历史记录。<br />
 */
function addPlay(music, {type = "one", isPlay = true, isAddHistory = true} = {}) {
    if (isPlay) {
        init({isKeepUrl: false});
        let musicPlay;
        let index = musicList.length;
        if ("list" === type) {
            // 添加到播放列表
            musicList.push(...music)
            // 更改封面及音乐人
            musicPlay = music[0]
        } else {
            //debugger;
            musicList.push(music)
            musicPlay = music
        }
        console.log("musicList", musicList)
        play({music: musicPlay, index: index, isAddHistory: isAddHistory});
    } else {
        if ("list" === type) {
            musicList.push(...music);
        } else {
            musicList.push(music);
        }
    }
}

/**
 * 第三步<br />
 * 标题：播放音乐，播放按钮一定要做节流
 *
 * 变量：first，第一次播放<br />
 * 变量：music，音乐原文件<br />
 * 变量：index，<br />
 * 变量：id，音乐id<br />
 * 变量：url，音乐路径<br />
 * 变量：isAddHistory，是否添加播放记录<br />
 */
function play({first = false, music, index = -1, id, url, isAddHistory = true} = {}) {

    if (first) {
        if (musicList.length >= 1) {
            audio.src = musicList[0].url;
            prepare(musicList[0]);
            assist(0);
        }
    } else if (music) {
        prepare(music);
        audio.src = music.url;
        assist(index, {id: music.id});
    } else if (id) {
        for (let i = 0; i < musicList.length; i++) {
            let music = musicList[i];
            if (music.id === id) {
                prepare(music);
                audio.src = music.url;
                assist(i, {id: id});
            }
        }
    } else if (url) {
        audio.src = music.url;
        assist(-1);
    }

    /**
     * 标题：辅助播放
     *
     * 变量：<br />
     */
    function assist(index, {id, url = audio.src} = {}) {
        audio.play().then(
            () => {
                player.isPlaySuccess = 1;
                player.isPlay = true;
                player.id = id;
                musicListIndex = index;
                // 播放时长
                player.duration = Math.floor(audio.duration)
                openTimer()
            },
            () => {
                // init();
                player.isPlaySuccess = 0;
                setHistory({id: id, url: url})
            }
        )
    }
}

/**
 * 标题：监视器，监视播放进度
 *
 * 变量：<br />
 */
function openTimer() {
    timer = setInterval(() => {
        //console.log("主进程在播放")
        console.log("播放列表数量：" + musicList.length, "当前播放：" + musicListIndex)
        // 获取播放器当前进度，单位：秒
        player.currentTime = Math.floor(audio.currentTime);
        let timeRanges = audio.buffered;
        // 获取以缓存的时间
        let timeBuffered = audio.buffered.end(timeRanges - 1);
        // 获取播放器缓存进度，单位：秒
        player.cache = Math.floor(timeBuffered);
        //player.imageSpeed++;
        //console.log(player)
        if (player.currentTime && player.duration <= player.currentTime) {
            done();
        }
    }, 101)
}

// 音乐播放器播放和暂停
function playPause() {
    if (player.isPlay) {
        if (audio.paused) {
            // 播放
            audio.play();
            openTimer();
            return 1;
        } else if (audio.play()) {
            //暂停
            audio.pause();
            clearInterval(timer);
            return 2;
        }
    }
    return 0;
}

// 暂停音乐播放器
function suspend() {
    clearInterval(timer)
}

// 调整音乐播放器进度
function adjust(currentTime) {
    audio.currentTime = currentTime
    openTimer()
}

// 上一首
function last() {
    if (musicList.length > 0 && musicListIndex - 1 >= 0) {
        musicListIndex++;
        play({music: musicList[musicListIndex], index: musicListIndex});
    }
}

// 下一首
function next() {
    if (musicList.length > 0 && musicList.length - 1 > musicListIndex) {
        musicListIndex--;
        play({music: musicList[musicListIndex], index: musicListIndex});
    }
}

// 播放完成后
function done() {
    init({index: musicListIndex});
    switch (player.playStart) {
        case 0:
            next();
            break;
        case 1:
            play({music: musicList[musicListIndex], index: musicListIndex});
            break;
        case 2:
            if (musicList.length > 0) {
                musicListIndex = Math.floor(Math.random() * musicList.length);
                play({music: musicList[musicListIndex], index: musicListIndex});
            }
            break;
    }
}

/**
 * 标题：如果音乐存在于收藏夹，将在收藏夹标记为不能播放的音乐
 *
 * 变量：id，音乐ID<br />
 */
function cannotPlay(id) {
    let collectionListJson = getLocalStorageJson("collectionList");
    try {
        collectionListJson.forEach((collection) => {
            if (id && collection.id === id) {
                collection.isPlay = false;
                // 满足条件，跳出循环
                throw new Error('true');
            }
        })
    } catch (e) {
        if (e.message !== "true") throw e
    }
    localStorage.setItem("collectionList", JSON.stringify(collectionListJson));
}

/**
 * 标题：重置播放器
 *
 * 变量：isKeepUrl，是否保留路径<br />
 */
function init({isKeepUrl, index = -1} = {}) {
    // 关闭计时器
    clearInterval(timer)
    // 更改播放id
    player.id = -1
    // 更改播放状态
    player.isPlay = false
    // 更改播放成功状态
    player.isPlaySuccess = -1
    // 重置播放进度
    player.currentTime = 0
    // 重置总时长
    player.duration = 0
    // 重置缓存进度条
    player.cache = 0
    // 重置标题
    player.title = '未知歌名'
    // 重置歌手
    player.artist = '未知歌手'
    // 重置专辑
    player.album = '未知专辑'
    // 重置播放路径
    player.url = isKeepUrl ? player.url : ''
    // 重置封面
    player.image = BACKGROUND_IMAGE
    // 重置播放列表
    musicListIndex = index
}


function removeHistory(music) {

}


/**
 * 标题：播放器播放前准备工作
 *
 * 变量：musicInfo，当前播放的音乐信息<br />
 */
function prepare(musicInfo) {
    player.title = musicInfo.title
    player.artist = musicInfo.artist
    player.album = musicInfo.album
    player.url = musicInfo.url
    player.image = musicInfo.image ? musicInfo.image : BACKGROUND_IMAGE;
}

// 获取当前播放的id
function getPlayId() {

}

// 修改音乐状态为不能播放
/**
 * 标题：把音乐收藏或取消收藏
 *
 * 变量：<br />
 */
function setMusicPlaying({id, url}) {
    let musicListJson = getLocalStorageJson("musicList")
    let set = false;
    try {
        musicListJson.forEach((song) => {
            if (url && url === song.url) {
                song.isPlay = false;
                set = true;
                throw new Error('true');
            } else if (id && id === song.id) {
                song.isPlay = false;
                set = true;
                throw new Error('true');
            }
        })
    } catch (e) {
        if (e.message !== "true") throw e
    }

    if (set) {
        localStorage.setItem("musicList", JSON.stringify(musicListJson));
    }
}

/**
 * 标题：添加或移除历史记录
 *
 * 变量：<br />
 */
export function setHistory(musicInfo, isHistory = true) {

    musicInfo.isPlaying = false;
    let historyListJson = getLocalStorageJson("historyList");

    if (isHistory) {
        historyListJson = historyListJson.filter((song) => {
            // 如果记录重复将去重
            return musicInfo.id !== song.id;
        })
        // 历史记录不能超过100条
        if (historyListJson.length >= 100) {
            historyListJson.length = 99;
        }
        historyListJson.unshift(musicInfo);
    } else {
        let keyWord = musicInfo.id;
        historyListJson = historyListJson.filter((collection) => {
            return keyWord !== collection.id;
        })
    }
    localStorage.setItem("historyList", JSON.stringify(historyListJson))
}

/**
 * 标题：把音乐收藏或取消收藏
 *
 * 变量：<br />
 */
export function setCollection(musicInfo, isCollection = true) {
    // 取消播放状态
    musicInfo.isPlaying = false;
    //let keyWord = "local" === songSheet.type ? musicInfo.url : musicInfo.id;
    let keyWord = musicInfo.id;

    let collectionListJson = getLocalStorageJson("collectionList");
    if (isCollection) {
        musicInfo.isCollection = true;
        //delete musicInfo.isPlaying;
        collectionListJson.unshift(musicInfo);
    } else {
        musicInfo.isCollection = false;
        collectionListJson = collectionListJson.filter((collection) => {
            return keyWord !== collection.id;
        })
    }
    localStorage.setItem("collectionList", JSON.stringify(collectionListJson))
}

/**
 * 标题：读取收藏夹，并添加收藏标记，播放标记，是否加载完成标记
 *
 * 变量：songList，歌曲列表<br />
 */
export function addMark(songList) {
    let collectionListJson = getLocalStorageJson("collectionList");
    let id = player.id;
    let i = 0;
    let songPlaying = -1;
    // 是否正在播放
    songList.forEach((song) => {
        // 是否加载完成
        song.isLoading = false;
        if ('-1' === id) {
            song.isPlaying = false;
        } else {
            if (song.id === id) {
                songPlaying = i;
                song.isPlaying = true
            } else {
                song.isPlaying = false
            }
        }

        // 是否已收藏
        collectionListJson.forEach((collection) => {
            if (!song.isCollection) {
                if (song.id === collection.id) {
                    song.isCollection = collection.isCollection;
                } else {
                    song.isCollection = false;
                }
            }
        })
        i++;
    })

    return songPlaying;
}

export default {
    player,
    play,
    playPause,
    addPlay,
    last,
    next,
    suspend,
    adjust,
    playModal,
}
/*return {
    audio,
    progressBar,
    musicImg,
    player,
    schedule,
    progress,
    max,
    play,
    playStart,
    changeMusic,
    suspend,
    adjust
}*/

